<template>
    <lay-card>
      <lay-container>
        <lay-layer v-model="visible" :area="['500px', '450px']">
          <EditNews></EditNews>
        </lay-layer>
        <lay-row space="20">
          <lay-col style="margin-top: 20px">
            <lay-form :model="queryForm" :pane="true" ref="layFormRef5" required>
              <lay-row space="1">
                <lay-col md="5">
                  <lay-form-item label="市场" mode="inline" prop="protocol">
                    <lay-select v-model="queryForm.market" class="inputDiv" placeholder="请选择">
                      <lay-select-option :value="item.value" :label="item.value" v-for="item in markets"></lay-select-option>
                    </lay-select>
                  </lay-form-item>
                </lay-col>
                <lay-col md="5">
                  <lay-form-item label="行情源" mode="inline" prop="protocol">
                    <lay-select v-model="queryForm.protocol" @change="exchangeProtocol" class="inputDiv" placeholder="请选择">
                      <lay-select-option :value="item.value" :label="item.value" v-for="item in protocols"></lay-select-option>
                    </lay-select>
                  </lay-form-item>
                </lay-col>
<!--                <lay-col md="14">-->
<!--                  <lay-form-item label="时间区间" mode="inline" prop="rangeTime">-->
<!--                   <lay-date-picker  v-model="queryForm.rangeTime" range type="datetime" placeholder="请选择"></lay-date-picker>-->
<!--                  </lay-form-item>-->
<!--                </lay-col>-->
                <lay-col md="6">
                  <lay-form-item label="起始时间" mode="inline" prop="beginTime">
                   <lay-date-picker  v-model="queryForm.beginTime" type="datetime" placeholder="请选择"></lay-date-picker>
                  </lay-form-item>
                </lay-col>
                <lay-col md="6">
                  <lay-form-item label="终止时间" mode="inline" prop="endTime">
                   <lay-date-picker  v-model="queryForm.endTime" type="datetime" placeholder="请选择"></lay-date-picker>
                  </lay-form-item>
                </lay-col>
              </lay-row>
              <lay-row>
                <lay-col md="5">
                  <lay-form-item label="编号" mode="inline">
                    <lay-input v-model="queryForm.rowNo" class="inputDiv" placeholder="请输入"></lay-input>
                  </lay-form-item>
                </lay-col>
                <lay-col md="5">
                  <lay-form-item label="证券代码" mode="inline">
                    <lay-input v-model="queryForm.securityId" class="inputDiv" placeholder="请输入"></lay-input>
                  </lay-form-item>
                </lay-col>
<!--                <lay-col md="5">-->
<!--                  <lay-form-item label="消息类型" mode="inline">-->
<!--                    <lay-select-->
<!--                      v-model="queryForm.types"-->
<!--                      placeholder="请选择"-->
<!--                      multiple-->
<!--                      allow-clear-->
<!--                      class="inputDiv"-->
<!--                    >-->
<!--                      <lay-select-option :value="item.value" :label="item.name" v-for="item in mysTypes"></lay-select-option>-->
<!--                    </lay-select>-->
<!--                  </lay-form-item>-->
<!--                </lay-col>-->
              </lay-row>
              <lay-row>
                <lay-col md="12">
                  <lay-button type="normal" @click="queryBatFiles">查询</lay-button>
                  <lay-button @click="resetFrom">重置</lay-button>
                  <lay-button @click="deleteRow(null, true)" type="danger">批量删除</lay-button>
                </lay-col>
                <lay-col md="12">
                  <vxe-button type="text" status="primary">
                    总数[{{page.total}}] 当前第 [{{page.current}}] 页共 [{{page.size}}] 条消息 剩余 [{{page.other}}] 条
                  </vxe-button>
                  <vxe-button type="info" @click="loadNextBatchData">下一页</vxe-button>
                </lay-col>
              </lay-row>
            </lay-form>
          </lay-col>
        </lay-row>
        <lay-row space="20">
          <lay-col md="24">
            <vxe-table
              ref="newsTable"
              border
              :loading="loading"
              show-overflow
              height="500"
              :row-config="{isHover: true}"
              :data="dataSource"
              :scroll-y="{enabled: true}">
              <vxe-column type="checkbox" width="3%"></vxe-column>
              <vxe-column field="rowNo" title="编号" width="10%" sortable></vxe-column>
              <vxe-column field="orgTime" title="消息时间" width="10%"></vxe-column>
              <vxe-column field="securityId" title="证券代码" width="10%"></vxe-column>
              <vxe-column field="msgType" title="类型" width="20%">
                <template #default="{row}">
                  <a>{{msgTypeDict[row?.msgType]}}</a>
                </template>
              </vxe-column>
              <vxe-column field="groupId" title="分组ID" width="15%" v-if="protocolCurrent === 'step'"></vxe-column>
              <vxe-column field="headData" title="消息头" width="25%" v-if="protocolCurrent === 'step'"></vxe-column>
              <vxe-column field="rawData" title="消息体" width="30%" show-overflow="title">
                <template #default="{row}">
                  <a>{{row?.rawData}}</a>
                </template>
              </vxe-column>
              <vxe-column title="操作" fixed="right" width="15%">
                <template #default="{row}">
                  <vxe-button size="mini" status="primary" @click="updateRow(row, false)">更新</vxe-button>
                  <vxe-button size="mini" status="info" @click="updateRow(row, true)">复制新增</vxe-button>
                  <vxe-button size="mini" status="danger" @click="deleteRow(row, false)">删除</vxe-button>
                </template>
              </vxe-column>
            </vxe-table>
          </lay-col>
        </lay-row>
      </lay-container>
    </lay-card>
</template>

<script lang="ts">

export default {
  name: "News"
}
</script>

<script lang="ts" setup>

import {onMounted, reactive, ref, h, onBeforeUnmount, onBeforeMount} from "vue";
import {notify} from "../../../untils/tip";
import {countNews, deleteNews, queryNews} from "../../../api/market/market";
import {getConfig} from "../../../api/market/basic";
import {layer} from "@layui/layui-vue";
import EditNews from "../../../components/Market/EditNews.vue";
import {BinaryInterface, BinaryNews} from "../../../store/market/BinaryInterface";

const loading = ref(false);
const selectedKeys = ref([]);
// const rangeTime = ref([]);
const dataSource = ref<BinaryNews[]>([]);
const visible = ref(false);
const newsTable = ref();
const protocolCurrent = ref("binary");
const layFormRef5 = ref();

// 页面加载前查询数据
onBeforeMount(()=>{
  getSelectItems('msgTypes');
  getSelectItems('market');
  getSelectItems('protocol');
  initLoadData();
})


// 页面关闭
onBeforeUnmount(()=>{
  localStorage.setItem("queryFormOfNews", JSON.stringify(queryForm));
})

const initLoadData = () => {
  const queryFormOfNews = localStorage.getItem("queryFormOfNews");
  console.log("queryFormOfNews:", queryFormOfNews);
  if(queryFormOfNews){
    const queryFormNews = JSON.parse(queryFormOfNews);
    queryForm.rowNo = queryFormNews.rowNo;
    queryForm.market = queryFormNews.market;
    queryForm.protocol = queryFormNews.protocol;
    queryForm.msgType = queryFormNews.msgType;
    queryForm.securityId = queryFormNews.securityId;
    queryForm.beginTime = queryFormNews.beginTime;
    queryForm.endTime = queryFormNews.endTime;
    queryForm.tableName = queryFormNews.tableName;
    queryForm.isWeb = queryFormNews.isWeb;
    queryForm.pageNo = queryFormNews.pageNo;
    queryForm.pageSize = queryFormNews.pageSize;
    queryForm.rangeTime = queryFormNews.rangeTime;
    if(queryForm.protocol !== null &&
      queryForm.market !== null &&
      queryForm.beginTime !== '' &&
      queryForm.endTime !== '' ){
      loadDataSource();
    }else {
      notify("failed", "必填项为空，请检查！");
    }
  }
};

// 下拉框选择的值
const industries: any = ref([]);
const markets: any = ref([]);
const protocols: any = ref([]);
const mysTypes : any = ref([]);

const page = reactive({
  current: 0,  // 请求次数
  limit: 1000,
  total: 0, // 总数
  size: 0 , // 当次请求的总数
  other: 0  // 剩余的数量
});

const queryForm: any = reactive({
    rowNo: null,
    market: null,
    protocol: null,
    msgType: [],
    rangeTime: [],
    securityId: null,
    beginTime: '',
    endTime: '',
    tableName: null,  // 当前表，第一次传入空
    isWeb: true,      // web调用
    pageNo: 0,        // 偏移量
    pageSize: page.limit
});

const queryBatFiles = async () => {
  if(queryForm.protocol !== null &&
      queryForm.market !== null &&
      queryForm.beginTime !== '' &&
      queryForm.endTime !== '' ){
    protocolCurrent.value = queryForm.protocol;
    page.current = 0;
    page.limit = 1000;
    queryForm.tableName = null;
    queryForm.pageNo = 0;
    openLoad();
    await queryFilesCount();
    closeLoad();
  }else {
    notify("failed", "必填项为空，请检查！");
  }
}

// 加载数据
const loadId = ref();
const openLoad = function() {
    loading.value = true;
    loadId.value = layer.load(0, { time: 60000 })
}

const closeLoad = () => {
    loading.value = false;
    layer.close(loadId.value);
}

const loadNextBatchData = () => {
  if(page.other <= 0){
    notify("success", "当前条件已经是最后一页了，没有数据了！");
  }else {
    openLoad();
    setTimeout(() => {
      loadDataSource();
      closeLoad();
    }, 5000);
  }
};

const resetFrom = () => {
  queryForm.msgType = [];
  queryForm.securityId = null;
  queryForm.protocol = null;
  queryForm.market = null;
  queryForm.beginTime = '';
  queryForm.endTime = '';
  queryForm.tableName = null;
  queryForm.pageNo = 0;
  queryForm.rangeTime = [];
};

const queryFilesCount = async () => {
  let {data, code, message} = await countNews(queryForm)
  if(code === 200){
    page.total = data;  // 总数
    page.other = data;  // 剩余数量
    await loadDataSource();
  }else {
    notify('fail', message);
  }
};

const loadDataSource = async () => {
  dataSource.value = [];
  queryForm.pageSize = page.limit;
  page.current = page.current + 1;
  // const $table = newsTable.value
  let {code, data, message} = await queryNews(queryForm)
  if(code === 200){
    console.log(page, data.total)
    queryForm.tableName = data.query.tableName;   // 当前表
    queryForm.pageNo = data.query.pageNo;         // 在此表的便宜量
    page.size = data.total;
    // 计算剩余数量： 统计的总数量 - 前N次返回的数量 - 当前返回的数量
    page.other = page.total - (page.current - 1)*page.limit - data.total;
    dataSource.value = data.result;  // 数据
    console.log(page)
  }else {
    notify('fail', message);
  }
};
const layId = ref();
// 更新数据
const updateRow = (row: any, flag: boolean) => {
  console.log("updateRow:", flag, row);
  layId.value = layer.open({
      type: "page",
      title: "行情消息",
      area: ["35%", "70%"],
      content: h(EditNews, {
        protocol: protocolCurrent.value,
        flag: flag,
        news: row,
        cancel: (news: any) => {
          if(flag){
            // dataSource.value.push(news);
            queryBatFiles();  // 重新查询
          }else {
            row.rawData = news;
          }
          layer.close(layId.value);
        }
      })
  })
}



// 删除数据
const deleteRow = (news: any, batch: boolean) => {
  layer.confirm("你确认要删除这些数据么？",
  {
    btn: [
      {text:'确认', callback: (id: any) => {
        if(batch){
          deleteRowBatch();
        }else {
          deleteRowApi(news);
        }
        layer.close(id); }
      },
      {text:'取消', callback: (id: any) => {
          layer.close(id); }
      }
      ]
    }
  );
};

// delete batch
const deleteRowBatch = () => {
  const $table = newsTable.value
  if ($table) {
    const selectRecords = $table.getCheckboxRecords()
    console.log("selectRecords:", selectRecords)
    selectRecords.forEach((unit: any) => {
      deleteRowApi(unit);
    })
  }
}

const deleteRowApi = async (news: any) => {
  const params: BinaryInterface = reactive<BinaryInterface>({
    protocol: protocolCurrent.value,
    tableName: news.tableName,
    id: news?.rowNo,
    rawData: ""
  })
  let {code, data, message} = await deleteNews(params);
  if(code === 200){
    const $table = newsTable.value;
    $table.remove(news);
    notify('success', "删除成功" + data + "条");
  }else {
    notify('fail', "删除失败");
  }
};

const exchangeProtocol = () => {
  if(queryForm.protocol !== null && queryForm.protocol === "binary"){
    getSelectItems("msgTypes");
  }else {
    getSelectItems("stepMsgTypes");
  }
};


// 获取下拉列表选择的值
const msgTypeDict: any = reactive({});
const getSelectItems = async (target: string) => {
  let {data, code, message} = await getConfig({target: target})
  if(code === 200){
    switch (target) {
      case 'market': markets.value = data; break;
      case 'industry': industries.value = data; break;
      case 'msgTypes':
        mysTypes.value = data;
        data.forEach((unit:any) => {msgTypeDict[unit.value] = unit.description})
        break;
      case 'stepMsgTypes':
        data.forEach((unit:any) => {msgTypeDict[unit.value] = unit.description})
        mysTypes.value = data;
        break;
      case 'protocol': protocols.value = data; break;
    }
  }else {
    notify('fail', message);
  }
};

</script>

<style scoped>
.inputDiv {
  width: 100%;
}

.row-content {
    width: 50%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space:nowrap;
    color: #01aaed;
}
</style>